package cn.schoolwow.util.module.query.jsonarray.flow.filter;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.module.query.jsonarray.domain.JSONArrayQueryOption;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Comparator;

public class FilterJSONArrayByOrderByFieldNameFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        JSONArrayQueryOption jsonQueryOption = flowContext.checkInstanceData(JSONArrayQueryOption.class);
        JSONArray filterArray = (JSONArray) flowContext.getData("filterArray");

        if(null==jsonQueryOption.orderByAscFieldName&&null==jsonQueryOption.orderByDescFieldName){
            return;
        }
        if(null!=jsonQueryOption.orderByAscFieldName){
            filterArray.sort(new Comparator<Object>() {
                @Override
                public int compare(Object o1, Object o2) {
                    JSONObject obj1 = (JSONObject) o1;
                    JSONObject obj2 = (JSONObject) o2;
                    Comparable fieldValue1 = (Comparable) obj1.get(jsonQueryOption.orderByAscFieldName);
                    Comparable fieldValue2 = (Comparable) obj2.get(jsonQueryOption.orderByAscFieldName);
                    if(null!=fieldValue1&&null!=fieldValue2){
                        return fieldValue1.compareTo(fieldValue2);
                    }
                    return null==fieldValue1?-1:1;
                }
            });
        }
        if(null!=jsonQueryOption.orderByDescFieldName){
            filterArray.sort(new Comparator<Object>() {
                @Override
                public int compare(Object o1, Object o2) {
                    JSONObject obj1 = (JSONObject) o1;
                    JSONObject obj2 = (JSONObject) o2;
                    Comparable fieldValue1 = (Comparable) obj1.get(jsonQueryOption.orderByDescFieldName);
                    Comparable fieldValue2 = (Comparable) obj2.get(jsonQueryOption.orderByDescFieldName);
                    if(null!=fieldValue1&&null!=fieldValue2){
                        return fieldValue2.compareTo(fieldValue1);
                    }
                    return null==fieldValue1?1:-1;
                }
            });
        }
    }

    @Override
    public String name() {
        return "指定JSONArray顺序";
    }

}
